/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cmti.skeleton.web.controller;

import com.cmti.skeleton.dto.SysDeptDto;
import com.cmti.skeleton.dto.SysLogDto;
import com.cmti.skeleton.dto.SysRoleDto;
import com.cmti.skeleton.dto.SysUserDto;
import com.cmti.skeleton.dto.TreeNode;
import com.cmti.skeleton.entity.SysLog;
import com.cmti.skeleton.entity.SysRole;
import com.cmti.skeleton.entity.SysUser;
import com.cmti.skeleton.service.DeptService;
import com.cmti.skeleton.service.RoleService;
import com.cmti.skeleton.service.SysDictService;
import com.cmti.skeleton.service.UserService;
import com.cmti.skeleton.util.Constants;
import com.cmti.skeleton.web.SysLogInterceptor;
import com.github.pagehelper.Page;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

/**
 *
 * @author Worker
 */
@Controller
@RequestMapping("/user")
@SessionAttributes(Constants.DEPTLIST_JSON)
public class UserController {

    private final Log log = LogFactory.getLog(getClass());
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private DeptService deptService;
    @Autowired
    SysDictService dictService;
//    @Autowired
//    private CommonDao commonDao;

    @RequestMapping("/list/ui")
    @RequiresPermissions("user:list:ui")
    public String listUI() {
        return "sys/user";
    }

    @RequestMapping("/list/data")
    @RequiresPermissions("user:list:*")
    public void listData(SysUserDto SysUserDto, ModelMap model) {
        Page<SysUserDto> page = (Page<SysUserDto>) userService.getUserList(SysUserDto);
        List<SysUserDto> userList = page.getResult();
        long totalUser = page.getTotal();

        model.addAttribute("rows", userList);
        model.addAttribute("total", totalUser);
    }

    /**
     * 使用layui时调用
     *
     * @param SysUserDto
     * @param model
     * @param limit
     */
    @RequestMapping("/list/dataL")
    @RequiresPermissions("user:list:*")
    public void listDataL(SysUserDto SysUserDto, ModelMap model, @RequestParam(value = "limit", defaultValue = "10") int limit) {
        SysUserDto.setRows(limit);
        Page<SysUserDto> page = (Page<SysUserDto>) userService.getUserList(SysUserDto);
        List<SysUserDto> userList = page.getResult();
        long totalUser = page.getTotal();

        model.addAttribute("code", 0).addAttribute("msg", "").addAttribute("data", userList).addAttribute("count", totalUser);
    }

    @RequestMapping("/add/ui")
    @RequiresPermissions("user:add:*")
    public void addUserUi(ModelMap model, HttpSession session) {
    }

    //增加用户
    @RequestMapping("/add/user")
    @RequiresPermissions("user:add:*")
    public void addUser(SysUserDto sysUserDto, ModelMap model, HttpServletRequest request) {
        boolean i = false;
        sysUserDto.setPassword("123"); //默认密码

        // 准备日志实例
        StringBuilder logContent = new StringBuilder();
        logContent.append("添加用户 ").append(sysUserDto.getAccount()).append("(")
                .append(sysUserDto.getName()).append(")");
        SysLogDto sysLog = SysLogInterceptor.generateSysLog(request, SysLog.TYPE_OPERATE, logContent.toString());

        try {
            i = userService.addUser(sysUserDto);
            model.put("ifAdd", i);
        } catch (DuplicateKeyException e) {
            sysLog.setException(e);
            sysLog.setResult(SysLog.RESULT_FAIL);
            model.addAttribute("ifAdd", i).addAttribute("msg", "用户账号重复!");
        }

    }

    /**
     * 显示部门树状结构
     *
     * @param writer
     * @param sysDeptDto
     * @throws IOException
     *
     */
    @RequestMapping("/add/deptTree")
    public void genDeptTree(Writer writer, SysDeptDto sysDeptDto, HttpSession session) throws IOException {

        List<TreeNode> deptJsonList = new ArrayList<TreeNode>();
        //定义部门列表字符串
        String deptListString;
        //如果session中存在
        if (session.getAttribute(Constants.DEPTLIST_JSON) != null) {
            deptListString = new ObjectMapper().writeValueAsString(session.getAttribute(Constants.DEPTLIST_JSON));
        } else {
            deptJsonList = deptService.getDeptTree();
            //将部门列表json保存在session中
            session.setAttribute(Constants.DEPTLIST_JSON, deptJsonList);
            deptListString = new ObjectMapper().writeValueAsString(deptJsonList);
        }

        writer.write(deptListString);
        writer.close();
    }

    /**
     * 显示部门树状结构（包括无上级部门的）
     *
     * @param writer
     * @throws IOException
     */
    @RequestMapping("/list/ui/deptTree")
    @RequiresPermissions("user:list:*")
    public void getDepartmentTreeAsJsonString(Writer writer, HttpSession session) throws IOException {

        //获取顶级部门
        SysDeptDto sysDeptDto = new SysDeptDto();

        List<TreeNode> deptJsonList = new LinkedList<TreeNode>();

        //如果session中存在
        if (session.getAttribute(Constants.DEPTLIST_JSON) != null) {
            deptJsonList = (List<TreeNode>) session.getAttribute(Constants.DEPTLIST_JSON);
        } else {
            deptJsonList = deptService.getDeptTree();
            //将部门列表json保存在session中
            session.setAttribute(Constants.DEPTLIST_JSON, deptJsonList);
        }

        // 新建一个List对象
        LinkedList<TreeNode> deptTree = new LinkedList<TreeNode>(deptJsonList);
        // 增加“无”选项
        TreeNode treeNode = new TreeNode();
        Map<String, Object> noParentDept = new HashMap<String, Object>();
        treeNode.setId(0);
        treeNode.setText("不限");
        noParentDept.put("iconCls", "icon-undo");
        treeNode.setAttributes(noParentDept);
        deptTree.addFirst(treeNode);
        writer.write(new ObjectMapper().writeValueAsString(deptTree));
        writer.close();
    }

    @RequestMapping("/list/role")
    @RequiresPermissions("user:list:*")
    public void listRole(SysRoleDto sysRoleDto, ModelMap model) {
        sysRoleDto.setStatus(0);
        sysRoleDto.setRows(Integer.MAX_VALUE); // 选取全部记录
        Page<SysRoleDto> page = (Page<SysRoleDto>) roleService.getRoles(sysRoleDto);
        List<SysRoleDto> sysRoleList = page.getResult();
//        long totalRole = page.getTotal();
        model.addAttribute("rows", sysRoleList);
//        model.addAttribute("total", totalRole);
    }

    //用户详细信息
    @RequestMapping(value = "/detail/ui")
    @RequiresPermissions("user:detail:*")
    public void detailUi() {
    }

    @RequestMapping(value = "/detail/user")
    @RequiresPermissions("user:detail:*")
    public void userInfo(HttpServletRequest request, ModelMap model) {
        List<SysRole> roleList = null;
        Map roleMap = new HashMap();
        int i = 0;
        String userId = request.getParameter("userId");
        roleList = roleService.queryRoleList(Long.valueOf(userId));
        for (SysRole r : roleList) {
            roleMap.put("rId" + i, r.getId());
            i++;
        }
        model.addAttribute("roleId", roleMap);

    }
    //修改用户

    @RequestMapping(value = "/modify/ui")
    @RequiresPermissions("user:modify:*")
    public void modifyUi(ModelMap model, HttpSession session) {
    }

    @ModelAttribute(Constants.DEPTLIST_JSON)
    public List<TreeNode> getDeptTree() {
        return deptService.getDeptTree();
    }

    @RequestMapping(value = "/modify/role")
    @RequiresPermissions("user:modify:*")
    public void modifyRole(HttpServletRequest request, ModelMap model) {
        List<SysRole> roleList = null;
        Map roleMap = new HashMap();

        int i = 0;
        String userId = request.getParameter("userId");
        roleList = roleService.queryRoleList(Long.valueOf(userId));
        for (SysRole r : roleList) {
            roleMap.put("rId" + i, r.getId());
            i++;
        }
        model.addAttribute("roleId", roleMap);
    }

    @RequestMapping(value = "/modify/user")
    @RequiresPermissions("user:modify:*")
    public void modifyUser(SysUserDto user, ModelMap model, HttpServletRequest request) {
        boolean i = false;

        SysUser newUser = userService.getSysUserById(user.getId());
        // 准备日志实例
        StringBuilder logContent = new StringBuilder();
        logContent.append("修改用户 ").append(newUser.getAccount()).append("(")
                .append(newUser.getName()).append(") 的用户信息");
        SysLogDto sysLog = SysLogInterceptor.generateSysLog(request, SysLog.TYPE_OPERATE, logContent.toString());

        // 账号和密码不能修改
        user.setAccount(null);
        user.setPassword(null);
//        String[] ignore = new String[]{"account", "password"};
//        BeanUtils.copyProperties(user, newUser, ignore);
        try {
            i = userService.modifyUser(user);
            model.addAttribute("ifUpdate", i);
        } catch (DuplicateKeyException e) {
            sysLog.setException(e);
            sysLog.setResult(SysLog.RESULT_FAIL);
            model.addAttribute("ifAdd", i).addAttribute("msg", "用户账号重复!");
        }

    }

    @RequestMapping(value = "/delete/ui")
    @RequiresPermissions("user:delete:*")
    public void deleteUi() {
    }

    //删除用户
    @RequestMapping("/delete")
    @RequiresPermissions("user:delete:*")
    public void deleteUser(@RequestParam("userId") long userId, HttpServletRequest request) {
        // 要先获取原有的用户
        SysUser user = userService.getSysUserById(userId);
        // 准备日志实例
        StringBuilder logContent = new StringBuilder();
        logContent.append("删除用户 ").append(user.getAccount()).append("(")
                .append(user.getName()).append(")");
        SysLogInterceptor.generateSysLog(request, SysLog.TYPE_OPERATE, logContent.toString());

        userService.delUser(userId);
    }

    @RequestMapping(value = "/resetpwd/ui")
    @RequiresPermissions("user:resetpwd:*")
    public void resetPwdUi() {
    }

    //密码重置
    @RequestMapping("/resetpwd")
    @RequiresPermissions("user:resetpwd:*")
    public void resetPwd(@RequestParam("userId") long userId, HttpServletRequest request) {
        // 要先获取原有的用户
        SysUser user = userService.getSysUserById(userId);
        // 准备日志实例
        StringBuilder logContent = new StringBuilder();
        logContent.append("重置用户 ").append(user.getAccount()).append("(")
                .append(user.getName()).append(") 的密码");
        SysLogInterceptor.generateSysLog(request, SysLog.TYPE_OPERATE, logContent.toString());

        userService.resetPassword(userId, "123");
    }

    @RequestMapping("/modify/lockUser")
    @RequiresPermissions("user:modify:*")
    public void lockUserAction(@RequestParam("userId") long userId, @RequestParam("action") String action, HttpServletRequest request) {
        // 要先获取原有的用户
        SysUser user = userService.getSysUserById(userId);
        // 准备日志实例
        StringBuilder logContent = new StringBuilder();
        if ("lock".equals(action)) {
            logContent.append("锁定");
        } else if ("unlock".equals(action)) {
            logContent.append("激活");
        }
        logContent.append("用户 ").append(user.getAccount()).append("(")
                .append(user.getName()).append(")");
        SysLogInterceptor.generateSysLog(request, SysLog.TYPE_OPERATE, logContent.toString());

        userService.lockOrUnlock(userId, action);
    }
    //验证用户是否重复

    @RequestMapping(value = "/list/validUserNo")
    public void valiUserNo(@RequestParam("account") String account, ModelMap model) {
        boolean result = true;
        long i = 0;

        //帐户是否存在并且判断是否为空字符串
        i = userService.getValidCount(account);
        if (i == 1 || account.trim().length() <= 0) {
            result = false;
        }
//        out.write(String.valueOf(result));
        model.addAttribute("result", result).addAttribute("message", "该账户已存在，请重新输入！");

    }

    @ModelAttribute
    public void getPersonalCertificateTypes(ModelMap model) {
        model.addAttribute("perCertTypes", dictService.getDictListByCategory("per_cert_type"));
    }

    @RequestMapping("/list/userRole")
    public void userRole(SysRoleDto sysRole, @RequestParam("id") Long id, ModelMap model) {
        //获取所有的角色
        sysRole.setRows(100);
        List<SysRoleDto> roles = roleService.getRoles(sysRole);
        //根据用户id获取其角色id
        List<Long> roleIdByUserId = userService.getRoleIdByUserId(id);
        ArrayList<Map> arrayList = new ArrayList<>();
        for (SysRoleDto role : roles) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", role.getId());
            map.put("name", role.getName());
            map.put("remark", role.getRemark());
            map.put("status", role.getStatus());
            for (Long long1 : roleIdByUserId) {
//                根据用户ID判断是否选中某个角色，如果选中设置LAY_CHECKED为true
                if (long1 == role.getId()) {
                    map.put("LAY_CHECKED", true);
                }
            }
            arrayList.add(map);
        }
        model.addAttribute("code", 0).addAttribute("msg", "").addAttribute("data", arrayList).addAttribute("count", roles.size());
    }
}
